<template>
  <div>
    <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
      :isFixedColumn="true" :columnWidth="140" :isMore="false" :isEndColumns="false" :footerBtnList="footerBtnList"
      :tableLoading="loading" :total="total" @pageSize="handlePageSize" @currentPage="handleCurrentPage">
      <!-- 条件组,插槽 -->
      <template #default>
        <el-form :inline="true" :model="formBtnList" class="demo-form-inline">
          <el-form-item label="">
            <el-select v-model="formBtnList.notice_type" clearable placeholder="通知类型" style="width: 180px"
              @change="handInquireYY">
              <el-option v-for="item in aOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="formBtnList.send" clearable filterable placeholder="状态" style="width: 180px"
              @change="handKey">
              <el-option v-for="item in languageOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-date-picker v-model="dateList" type="daterange" unlink-panels range-separator="-"
              start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" value-format="YYYY-MM-DD"
              format="YYYY-MM-DD" @change="handleDateChange" />
          </el-form-item>
        </el-form>
      </template>
    </Table>

    <!-- 弹窗 -->
    <DialogCom ref="dialogCom" :dialogVisible="dialogVisible" :btnLoading="btnLoading" :tableTitle="tableTitle"
      :formData="formData" :ruleForm="ruleForm" :rules="rules" :submitBtn="'保 存'" @beforeClose="beforeClose"
      @dialogSwitch="dialogSwitch" @submitForm="submitForm" />
  </div>
</template>

<script setup lang='ts' name="commodityMent">
import { ref, reactive, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import Table from '@/components/Table.vue';
import DialogCom from '@/components/DialogCom.vue';
import { Search } from '@element-plus/icons-vue'
import { noticeList, noticeDelete, noticeAdd, noticeAdmin, noticeSend } from '@/api/notice/notice.ts'
import { useRouteStore } from '@/stores/modules/counter.ts'
const routeStore = useRouteStore();
// 表格相关 开始
const loading = ref(false)
// const product_key = ref('');
// 表头数据
const columns = ref([
  { prop: 'notice_id', label: '通知ID', width: 140 },
  { prop: 'notice_type', label: '通知类型', width: 140, formatter: (row: any) => statusMap(row.notice_type) },
  { prop: 'notice_content', label: '通知内容', width: '' },
  { prop: 'send_time', label: '修改时间', width: 200 },
  // { prop: 'fsyhid', label: '发送用户ID', width: 180 },
  { prop: 'send', label: '状态', width: 120, formatter: (row: any) => row.send == '1' ? '发送成功' : '待发送' },
]);
const statusMap = ((data: string) => {
  switch (data) {
    case '1':
      return '系统公告';
    case '2':
      return '版本更新';
    case '3':
      return '上新通知';
    default:
      return '告警提醒';
  }
})
// 表格数据
// 判断依据: judData
const paginatedData = ref([])
// 查询条件
const formBtnList = reactive({
  // lang: routeStore.commodityMentLang ? routeStore.commodityMentLang : 'cn',
  notice_type: '',
  send: '',
  product_key: '',
  time_start: '',
  time_end: '',
  page_size: 10,
  page: 1,
})
let aOptions = ref([
  {
    value: '1',
    label: '系统公告',
  },
  {
    value: '2',
    label: '版本更新',
  },
  {
    value: '3',
    label: '上新通知',
  },
  {
    value: '4',
    label: '告警提醒',
  },
])
const dateList = ref([])
// 日期快速选择
const shortcuts = [
  {
    text: '近1周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近90天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
// 日期选择
const handleDateChange = () => {
  formBtnList.time_start = dateList.value[0]
  formBtnList.time_end = dateList.value[1]
}
let languageOptions = ref([
  {
    value: '0',
    label: '待发送',
  },
  {
    value: '1',
    label: '已发送',
  },
])
const handInquireYY = () => {
  routeStore.setCommodityMentLang(formBtnList.notice_type)
  // console.log(formBtnList.lang)
  handInquire()
}
const handKey = (val: string) => {
  handInquire()
}
const total = ref(0)
// 查询
const handInquire = () => {
  loading.value = true
  noticeList(formBtnList, 'cn').then((res: any) => {
    if (res.code === 200) {
      total.value = res.data.total
      const processedData = res.data.notice.map((item: Object) => {
        return {
          ...item,
          judData: item.send  // 添加 judData 属性，并赋值为 send
        };
      });
      paginatedData.value = processedData
    } else {
      ElMessage.error(`请求错误: ${res.msg}`)
    }
  }).catch((error: any) => {
    ElMessage.error(`请求错误: ${error}`)
  }).finally(() => {
    loading.value = false
  })
}
interface RuleForm {
  notice_type: string;
  send_type: string;
  notice_content: string;
}
interface RuleFormItem {
  notice_type: string;
  send_type: string;
  notice_content: string;
}
// 表单数据
const ruleForm = ref<RuleFormItem>();
// 重置表单方法
const resetForm = (initialData?: Partial<RuleForm>) => {
  // console.log("🚀 ~ resetForm ~ initialData:", initialData)
  ruleForm.value = { notice_id: '', notice_type: '', notice_type1: '', send_type: '', notice_content: '' }
  if (initialData) {
    ruleForm.value = {
      notice_id: initialData.notice_id,
      notice_type: initialData.notice_type,
      notice_type1: initialData.notice_type1,
      send_type: initialData.send_type,
      notice_content: initialData.notice_content
    }
  }
  Object.assign(ruleForm, {
    notice_id: '',
    notice_type: '',
    notice_type1: '',
    send_type: '',
    notice_content: '',
    ...(initialData || {}),
  });
};
// 新增
const handAddAccount = () => {
  resetForm();
  tableTitle.value = '新增通知'
  dialogVisible.value = true
}
// 编辑
const handEditAccount = (row: object, index: number) => {
  resetForm(row);
  tableTitle.value = '编辑通知'
  dialogVisible.value = true
}
// 重置
const handDerived = () => {
  // console.log('重置')
  formBtnList.notice_type = ''
  formBtnList.product_key = ''
  formBtnList.send = ''
  formBtnList.time_start = ''
  formBtnList.time_end = ''
  dateList.value = []
  handInquire()
}
// 按钮组
const btnList = [
  { name: '查询', type: 'primary', click: handInquire, icon: '' },
  { name: '重置', type: 'success', click: handDerived, icon: '' },
]
const footerBtnList = [
  { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
]
// 删除
const reject = (row: object, index: number) => {
  ElMessageBox.confirm(
    '确定删除此项吗？',
    '删除',
    {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }
  ).then(() => {
    noticeDelete(row.notice_id).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: '成功',
          type: 'success',
        })
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
      }
    }).catch(() => {
    }).finally(() => {
      handInquire()
    })
  }).catch(() => {

  })
}
const radioItems = [// 通知类型 单选数据
  { label: '系统公告', value: '1' },
  { label: '版本更新', value: '2' },
  { label: '上新通知', value: '3' },
  { label: '告警提醒', value: '4' },
]
// 表单控件数据
let formData = reactive([
  { type: 'radio', label: '通知类型', prop: 'notice_type', span: 24, radioItems: radioItems },
  // { type: 'input', label: '发送用户ID', prop: 'send_type', span: 24, placeholder: '不输入默认ALL' },
  { type: 'textarea', label: '通知内容', prop: 'notice_content', span: 24, placeholder: '请输入', minRows: 8, maxRows: 8 },
])
// 发送按钮
const handSend = (row: object, index: number) => {
  ElMessageBox.confirm(
    '确定发送吗？',
    '发送',
    {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }
  ).then(() => {
    let para = {
      official_id: row.notice_id,
      official_content: row.notice_content,
    }
    noticeSend(para).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: '成功',
          type: 'success',
        })
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
      handInquire()
    })
  })
}
// 灰色按钮
const noHandSend = (row: object, index: number) => {
  ElMessage({
    message: '该通知已发送，操作无效',
    type: 'warning',
  })
}
// 详情
const handDetails = (row: object, index: number) => {
  formData = [
    { type: 'detailsText', label: '通知类型', prop: 'notice_type1', span: 24, radioItems: radioItems },
    // { type: 'detailsText', label: '发送用户ID', prop: 'send_type', span: 24, placeholder: '不输入默认ALL' },
    { type: 'detailsText', label: '通知内容', prop: 'notice_content', span: 24, placeholder: '请输入', minRows: 8, maxRows: 8 },
  ]
  row.notice_type1 = statusMap(row.notice_type)
  // row.send_type
  resetForm(row);
  tableTitle.value = '详情'
  dialogVisible.value = true
}
// 操作列按钮组
const btnListTable = ref([
  { name: '发送', type: 'success', click: handSend, color: '#DE868F', fontColor: '#fff', judgment: true, isShow: ['0'], },
  { name: '发送', type: 'info', click: noHandSend, judgment: true, isShow: ['1'], },
  // { name: '编辑', type: 'success', click: handEditAccount, judgment: true, isShow: ['0'], },
  // { name: '编辑', type: 'info', click: noHandSend, judgment: true, isShow: ['1'], },
  // { name: '详情', type: 'primary', click: handDetails },
  // { name: '删除', type: 'danger', click: reject, judgment: true, isShow: ['0'], },
  // { name: '删除', type: 'info', click: noHandSend, judgment: true, isShow: ['1'], },
  { name: '删除', type: 'danger', click: reject },
])
// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
  // console.log('handlePageSize', pageSize);
  formBtnList.page_size = pageSize
  handInquire()
};
const handleCurrentPage = (currentPage: number) => {// 页码
  // console.log('handleCurrentPage', currentPage);
  formBtnList.page = currentPage
  handInquire()
};
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();
const btnLoading = ref(false)
// 表单校验配置
const rules = reactive<FormRules<RuleForm>>({
  notice_content: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
  ],
  notice_type: [
    { required: true, message: '此项为必选项', trigger: 'blur' },
  ],
})
// 弹窗 确认按钮
const submitForm = ((ruleFormData: any) => {
  if (tableTitle.value === '新增通知') {
    btnLoading.value = true
    let para = {
      notice_content: ruleFormData.notice_content,
      notice_type: ruleFormData.notice_type,
      // send_type: '1',
    }
    noticeAdd(para).then((res: any) => {
      if (res.code === 200) {
        if (dialogCom.value) {
          dialogCom.value.cancelClick(); // 调用子组件方法
        }
        ElMessage({
          message: '成功',
          type: 'success',
        })
        handInquire()
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
        btnLoading.value = false
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
      btnLoading.value = false
    })
  } else if (tableTitle.value === '编辑通知') {
    let para = {
      notice_id: ruleFormData.notice_id,
      notice_type: ruleFormData.notice_type,
      // send_type: ruleFormData.send_type,
      // send_type: '1',
      notice_content: ruleFormData.notice_content,
    }
    btnLoading.value = true
    noticeAdmin(para).then((res: any) => {
      if (res.code === 200) {
        if (dialogCom.value) {
          dialogCom.value.cancelClick(); // 调用子组件方法
        }
        ElMessage({
          message: '成功',
          type: 'success',
        })
        handInquire()
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
        btnLoading.value = false
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
      btnLoading.value = false
    })
  }
})
// 弹窗标题
const tableTitle = ref('');
const dialogVisible = ref(false);
const beforeClose = () => {
  formData = [
    { type: 'radio', label: '通知类型', prop: 'notice_type', span: 24, radioItems: radioItems },
    // { type: 'input', label: '发送用户ID', prop: 'send_type', span: 24, placeholder: '不输入默认ALL' },
    { type: 'textarea', label: '通知内容', prop: 'notice_content', span: 24, placeholder: '请输入', minRows: 8, maxRows: 8 },
  ]
  tableTitle.value = ''
  dialogVisible.value = false;
}
const dialogSwitch = (row: object) => {
  console.log('row: ', row);

}

onMounted(() => {
  handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
  .el-input {
    width: 180px;

  }

  :deep(.el-date-editor) {
    width: 240px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 20px;
  }
}
</style>